package com.zc.im.service.im.group.impl;

import com.zc.im.mapper.im.group.ZcImDirectoryGroupMapper;
import com.zc.im.mapper.im.group.ZcImDirectoryMapper;
import com.zc.im.model.im.group.ZcImDirectory;
import com.zc.im.model.im.group.ZcImDirectoryExample;
import com.zc.im.model.im.group.ZcImDirectoryGroup;
import com.zc.im.model.im.group.ZcImDirectoryGroupExample;
import com.zc.im.model.user.ZcUser;
import com.zc.im.service.im.group.ImDirectoryService;
import com.zc.im.service.user.UserService;
import com.zc.im.util.ImGolbalTypeContext;
import com.zc.im.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * Created by Administrator on 2017/7/12.
 */
@Service
public class ImDirectoryServiceImpl implements ImDirectoryService{

    private final static Logger log = LoggerFactory.getLogger(ImDirectoryServiceImpl.class);

    @Autowired
    private ZcImDirectoryMapper imDirectoryMapper;

    @Autowired
    private ZcImDirectoryGroupMapper imDirectoryGroupMapper;

    @Autowired
    private UserService userService;


    /**
     * 添加通讯录
     * 2017-7-13 11:20:12
     * @param directory
     * @return
     */
    public Integer insertDirectory(ZcImDirectory directory){
        Integer backFlag = 0;
        if(directory == null){
            log.error("参数缺失");
            return backFlag;
        }
        //判断通讯录中是否存在好友
        ZcImDirectory currentDirectory = findDirectory(directory.getUserId(), directory.getFriendsId());
        if(currentDirectory != null){
            log.error("好友已经存在，无需重复添加.");
            return backFlag;
        }


        directory.setFriendsRelationFlag(setDirectoryFriendsRelationFlag(directory.getAddSource()));
        ZcImDirectoryGroup directoryGroup  = setDirectoryGroup(directory);
        if(directoryGroup != null){
            directory.setGroupId(directoryGroup.getId());
        }
        directory.setCreatedTime(new Date());
        directory.setUpdatedTime(new Date());
        directory.setStatus(ImGolbalTypeContext.STATUS_VALID);
        backFlag = imDirectoryMapper.insert(directory);

        //更新组成员数量
        if(directoryGroup != null){
            directoryGroup.setGroupPeopleNum(directoryGroup.getGroupPeopleNum() + 1);
            backFlag = updateDirectoryGroupById(directoryGroup);
        }
        return backFlag;
    }


    /**
     * 添加通讯录组
     * 2017-7-13 16:15:17
     * @return
     */
    public Integer insertDirectoryGroup(ZcImDirectoryGroup directoryGroup){
        Integer backStatus = 0;
        //判断组名是否存在
        if(directoryGroup == null){
            log.error("添加通讯录组数据为空.");
            return backStatus;
        }
        ZcImDirectoryGroup group = findDirectoryGroup(directoryGroup.getUserId(),null, directoryGroup.getGroupName());
        //添加组
        if(group == null){
            directoryGroup.setSupportModifyStatus(ImGolbalTypeContext.IM_DIRECTORY_GROUP_SUPPORT_MODIFY);
            directoryGroup.setGroupPeopleNum(0);
            directoryGroup.setGroupSort(findDirectoryGroupSort(directoryGroup.getUserId()));
            directoryGroup.setCreatedTime(new Date());
            directoryGroup.setUpdatedTime(new Date());
            directoryGroup.setStatus(ImGolbalTypeContext.STATUS_VALID);
            backStatus = imDirectoryGroupMapper.insertSelective(directoryGroup);
        }
        return backStatus;
    }

    /**
     * 设置朋友关联关系
     * 2017-7-12 20:23:38
     * @param addSource
     * @return
     */
    public String setDirectoryFriendsRelationFlag(String addSource){
        String friendsRelation =  null;
        if(StringUtils.isEmpty(addSource)){
            return friendsRelation;
        }
            //群组    通过群组添加就是同事
        if(ImGolbalTypeContext.IM_DIRECTORY_ADD_SOURCE_GROUP.equals(addSource)){
            friendsRelation = ImGolbalTypeContext.IM_DIRECTORY_FRIENDS_RELATION_TWO_WAY;
            //电话
        }else if(ImGolbalTypeContext.IM_DIRECTORY_ADD_SOURCE_PHONE.equals(addSource)){
            friendsRelation = ImGolbalTypeContext.IM_DIRECTORY_FRIENDS_RELATION_TWO_WAY;
            //真实姓名
        }else if(ImGolbalTypeContext.IM_DIRECTORY_ADD_SOURCE_NAME.equals(addSource)){
            friendsRelation = ImGolbalTypeContext.IM_DIRECTORY_FRIENDS_RELATION_TWO_WAY;
            //职位简历
        }else if(ImGolbalTypeContext.IM_DIRECTORY_ADD_SOURCE_POSITION_RESUME.equals(addSource)){
            friendsRelation = ImGolbalTypeContext.IM_DIRECTORY_FRIENDS_RELATION_ONE_WAY;
            //职位好友
        }else if(ImGolbalTypeContext.IM_DIRECTORY_ADD_SOURCE_POSITION_FRIENDS.equals(addSource)){
            friendsRelation = ImGolbalTypeContext.IM_DIRECTORY_FRIENDS_RELATION_TWO_WAY;
            //职位联系方式
        }else if(ImGolbalTypeContext.IM_DIRECTORY_ADD_SOURCE_POSITION_PHONE.equals(addSource)){
            friendsRelation = ImGolbalTypeContext.IM_DIRECTORY_FRIENDS_RELATION_TWO_WAY;
        }
        return friendsRelation;
    }


    /**
     * 添加默认的通讯录组
     * 2017-7-13 08:45:13
     * @param userId
     * @return
     */
    public String insertDefDirectoryGroup(Integer userId){
        StringBuffer directoryGroupStr = new StringBuffer();

        Integer defParentGroupId = 0;
        //同学    同事  同行
        ZcImDirectoryGroup parentClassmate = saveDefDirectoryGroup(userId, ImGolbalTypeContext.IM_DEF_DIRECTORY_GROUP_CLASSMATE_AND_SAME_INDUSTRY_AND_COLLEAGUE, defParentGroupId);
        //BOSS  部门负责人
        ZcImDirectoryGroup parentBoss = saveDefDirectoryGroup(userId, ImGolbalTypeContext.IM_DEF_DIRECTORY_GROUP_BOSS_MANAGER, defParentGroupId);

        //大学生
        saveDefDirectoryGroup(userId, ImGolbalTypeContext.IM_DEF_DIRECTORY_GROUP_CLASSMATE, defParentGroupId);
        //猎头公司
        saveDefDirectoryGroup(userId, ImGolbalTypeContext.IM_DEF_DIRECTORY_GROUP_HEAD_HUNTING_COMPANY, defParentGroupId);
        // 感兴趣的
        saveDefDirectoryGroup(userId, ImGolbalTypeContext.IM_DEF_DIRECTORY_GROUP_INTERESTED, defParentGroupId);
        // 未分组好友
        saveDefDirectoryGroup(userId, ImGolbalTypeContext.IM_DEF_DIRECTORY_GROUP_NON_GROUPED_FRIENDS, defParentGroupId);


        //  BOSS
        saveDefDirectoryGroup(userId, ImGolbalTypeContext.IM_DEF_DIRECTORY_GROUP_BOSS, parentBoss.getId());
        ///部门负责人
        saveDefDirectoryGroup(userId, ImGolbalTypeContext.IM_DEF_DIRECTORY_GROUP_DEPARTMENT_MANAGER, parentBoss.getId());
        //  同学
        saveDefDirectoryGroup(userId, ImGolbalTypeContext.IM_DEF_DIRECTORY_GROUP_CLASSMATE, parentClassmate.getId());
        // 同事
        saveDefDirectoryGroup(userId, ImGolbalTypeContext.IM_DEF_DIRECTORY_GROUP_COLLEAGUE, parentClassmate.getId());
        // 同行
        saveDefDirectoryGroup(userId, ImGolbalTypeContext.IM_DEF_DIRECTORY_GROUP_SAME_INDUSTRY, parentClassmate.getId());
        return directoryGroupStr.toString();
    }


    public ZcImDirectoryGroup saveDefDirectoryGroup(Integer userId, String groupName, Integer parentGroupId){

        ZcImDirectoryGroup haveGroup = findDirectoryGroup(userId, null, groupName);
        if(haveGroup != null){
            log.error("已经存在通讯录组");
            return haveGroup;
        }

        ZcImDirectoryGroup directoryGroup = new ZcImDirectoryGroup();
        directoryGroup.setParentGroupId(parentGroupId);
        directoryGroup.setUserId(userId);
        directoryGroup.setGroupName(groupName);
        directoryGroup.setGroupPeopleNum(0);
        directoryGroup.setGroupSort(findDirectoryGroupSort(userId));
        directoryGroup.setCreatedTime(new Date());
        directoryGroup.setUpdatedTime(new Date());
        directoryGroup.setStatus(ImGolbalTypeContext.STATUS_VALID);
        imDirectoryGroupMapper.insertSelective(directoryGroup);
        return directoryGroup;
    }


    /**
     * 查询当前用户通讯录组排序
     * 2017-7-13 09:06:23
     * @param userId
     * @return
     */
    public Integer findDirectoryGroupSort(Integer userId){
        ZcImDirectoryGroupExample groupExample = new ZcImDirectoryGroupExample();
        ZcImDirectoryGroupExample.Criteria criteria = groupExample.createCriteria();
        criteria.andUserIdEqualTo(userId);
        groupExample.setOrderByClause("group_sort desc");
        List<ZcImDirectoryGroup> directoryGroups = imDirectoryGroupMapper.selectByExample(groupExample);
        if(directoryGroups == null || directoryGroups.size() ==0){
            return 0;
        }
        ZcImDirectoryGroup directoryGroup = directoryGroups.get(0);
        return directoryGroup.getGroupSort();
    }




    /**
     * 查询好友信息设置分类
     * 2017-7-13 13:37:23
     */
    public ZcImDirectoryGroup setDirectoryGroup(ZcImDirectory directory){
        ZcImDirectoryGroup directoryGroup = null;
        if(directory.getGroupId() != null){
            return directoryGroup;
        }else{
            //获得当前用户的所有群组
            Map<String, ZcImDirectoryGroup> groupMap = queryDirectoryGroupMap(directory.getUserId());
            if(groupMap == null || groupMap.size() ==0){
                log.error("当前用户没有通讯录组 userId:{}", directory.getUserId());
                return directoryGroup;
            }
            ZcUser zcUser =  userService.findUser(directory.getFriendsId());
            if(zcUser == null){
                log.error("添加的朋友不存在  friendsId:{}", directory.getFriendsId());
                return directoryGroup;
            }

            //企业
            if(ImGolbalTypeContext.IM_USER_TYPE_COMPANY.equals(zcUser.getType())){
                directoryGroup = groupMap.get(ImGolbalTypeContext.IM_DEF_DIRECTORY_GROUP_BOSS);
            }
            //个人
            if(ImGolbalTypeContext.IM_USER_TYPE_PEOPLE.equals(zcUser.getType())){
                directoryGroup = groupMap.get(ImGolbalTypeContext.IM_DEF_DIRECTORY_GROUP_CLASSMATE);
            }
            //猎头
            if(ImGolbalTypeContext.IM_USER_TYPE_HEADHUNTING.equals(zcUser.getType())){
                directoryGroup = groupMap.get(ImGolbalTypeContext.IM_DEF_DIRECTORY_GROUP_HEAD_HUNTING_COMPANY);
            }
            //大学生
            if(ImGolbalTypeContext.IM_USER_TYPE_COLLEGE_STUDENT.equals(zcUser.getType())){
                directoryGroup = groupMap.get(ImGolbalTypeContext.IM_DEF_DIRECTORY_GROUP_COLLEGE_STUDENT);
            }
            //未分组
            if(directoryGroup == null){
                log.error("没有符合的通讯录组，分配到默认 未分组中");
                directoryGroup = groupMap.get(ImGolbalTypeContext.IM_DEF_DIRECTORY_GROUP_NON_GROUPED_FRIENDS);
            }
            if(directoryGroup == null){
                log.error("没有符合的通讯录组,初始化数据异常!");
                return directoryGroup;
            }
        }
        return directoryGroup;
    }




    /**
     * 获得当前用户的通讯录map
     * 2017-7-13 16:47:07
     * @return
     */
    public Map<String, ZcImDirectoryGroup> queryDirectoryGroupMap(Integer userId){
        Map<String, ZcImDirectoryGroup> groupMap = new HashMap<>();
        if(userId == null){
            return groupMap;
        }

        List<ZcImDirectoryGroup> directoryGroups = queryDirectoryGroups(userId);
        if(directoryGroups == null || directoryGroups.size() ==0){
            return groupMap;
        }
        for(ZcImDirectoryGroup group: directoryGroups){
            groupMap.put(group.getGroupName(), group);
        }
        return groupMap;
    }


    /**
     * 查询通讯录组
     * 2017-7-13 13:51:34
     * @param userId
     * @return
     */
    public List<ZcImDirectoryGroup> queryDirectoryGroups(Integer userId){
        List<ZcImDirectoryGroup> directoryGroups = new ArrayList<>();
        if(userId == null){
            return directoryGroups;
        }
        ZcImDirectoryGroupExample groupExample = new ZcImDirectoryGroupExample();
        ZcImDirectoryGroupExample.Criteria criteria = groupExample.createCriteria();
        criteria.andUserIdEqualTo(userId);
        criteria.andStatusEqualTo(ImGolbalTypeContext.STATUS_VALID);

        directoryGroups = imDirectoryGroupMapper.selectByExample(groupExample);
        return directoryGroups;
    }





    /**
     * 查询通讯录组
     * 2017-7-13 16:26:33
     * @return
     */
    public ZcImDirectoryGroup findDirectoryGroup(Integer userId, Integer groupId, String groupName){
        ZcImDirectoryGroup directoryGroup = null;
        if(userId == null || (StringUtils.isEmpty(groupName) && groupId == null) ){
            return directoryGroup;
        }
        ZcImDirectoryGroupExample groupExample = new ZcImDirectoryGroupExample();
        ZcImDirectoryGroupExample.Criteria criteria = groupExample.createCriteria();
        if(!StringUtils.isEmpty(groupName)){
            criteria.andGroupNameEqualTo(groupName);
        }
        if(groupId != null){
            criteria.andIdEqualTo(groupId);
        }
        if(userId!= null){
            criteria.andUserIdEqualTo(userId);
        }
        List<ZcImDirectoryGroup> groups = imDirectoryGroupMapper.selectByExample(groupExample);
        if(groups == null || groups.size() == 0){
            return directoryGroup;
        }
        directoryGroup = groups.get(0);
        return directoryGroup;
    }


    public Integer updateDirectoryGroupById(ZcImDirectoryGroup group){
        if(group == null){
            return 0;
        }
       return imDirectoryGroupMapper.updateByPrimaryKeySelective(group);
    }


    /**
     * 查询通讯录
     * 2017-7-14 15:13:49
     * @param userId
     * @param friendsId
     * @return
     */
    public ZcImDirectory findDirectory(Integer userId, Integer friendsId){
        ZcImDirectory directory = null;
        if(userId == null || friendsId == null){
            log.error("参数缺失, userId:{}, friendsId:{}", userId, friendsId);
            return directory;
        }

        //
        ZcImDirectoryExample directoryExample = new ZcImDirectoryExample();
        ZcImDirectoryExample.Criteria criteria = directoryExample.createCriteria();
        criteria.andUserIdEqualTo(userId);
        criteria.andFriendsIdEqualTo(friendsId);
        criteria.andStatusEqualTo(ImGolbalTypeContext.STATUS_VALID);

        List<ZcImDirectory> directories = imDirectoryMapper.selectByExample(directoryExample);
        if(directories == null || directories.size() == 0){
            return directory;
        }
        directory = directories.get(0);
        return directory;
    }
}
